package com.bluejie.bluej.cipher;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * Created by bluej on 2018-09-13.
 */
public class AESUtil {
    private final static String DEFAULT_CHARSET = "UTF-8";
    private final static String KEY_AES = "AES";
    private final static int KES_SIZE = 128;


    private static String doAES(String data,String key,int model){
        String cipherData = null;
        boolean encrptFlag = model== Cipher.ENCRYPT_MODE;
        byte[] content = null;
        try {
            if (encrptFlag){
                content = data.getBytes(DEFAULT_CHARSET);
            }else {
                content = Base64.getDecoder().decode(data);
            }

            KeyGenerator keyGenerator =KeyGenerator.getInstance(KEY_AES);
            keyGenerator.init(KES_SIZE, new SecureRandom(key.getBytes(DEFAULT_CHARSET)));
            SecretKey secretKey = keyGenerator.generateKey();

            Cipher cipher = Cipher.getInstance(KEY_AES);
            cipher.init(model,secretKey);
            byte[] result = cipher.doFinal(content);
            if (encrptFlag){
                cipherData = Base64.getEncoder().encodeToString(result);
            }else {
                cipherData = new String(result,DEFAULT_CHARSET);
            }
        }catch (Exception e){
            System.out.println("error:"+e);
        }
        return cipherData;
    }


    public static void main(String[] args) {
        String data = "2DDF的对方的";
        String key = "enter";
        String cipher = doAES(data,key,1);
        System.out.println(cipher);
        cipher = doAES(cipher,key,2);
        System.out.println(cipher);
    }
}
